import { THEME_CONFIG } from '@/themes/theme-config.js'

export default {
  namespaced: true, // 启用命名空间
  state: () => ({
    currentTheme: 'light',
    systemTheme: 'light' // 用于系统主题跟随
  }),
  mutations: {
    SET_THEME(state, theme) {
      state.currentTheme = theme
    },
    SYNC_SYSTEM_THEME(state, theme) {
      state.systemTheme = theme
    }
  },
  actions: {
    // 初始化主题（含多端处理）
    async initTheme({ commit, dispatch }) {
      const savedTheme = uni.getStorageSync('APP_THEME')
      const validTheme = savedTheme || 'light'
      
      // 处理APP端原生导航栏
      if (uni.getSystemInfoSync().platform === 'android') {
        dispatch('setNavigationBar', validTheme)
      }
      
      commit('SET_THEME', validTheme)
    },

    // 完整主题切换逻辑
    setTheme({ commit, state, dispatch }, theme) {
      return new Promise((resolve) => {
        const targetTheme = THEME_CONFIG[theme] ? theme : state.currentTheme
        
        // 多平台样式更新
        dispatch('updatePlatformStyles', targetTheme)
        
        commit('SET_THEME', targetTheme)
        uni.setStorageSync('APP_THEME', targetTheme)
        
        resolve(targetTheme)
      })
    },

    // 多端样式更新
    updatePlatformStyles({ state }, theme) {
      const config = THEME_CONFIG[theme]
      
	  // #ifdef H5
		// H5动态更新CSS变量
		Object.entries(config).forEach(([key, value]) => {
		  document.documentElement.style.setProperty(`--theme-${key}`, value)
		})
	  // #endif
      
	 // #ifdef MP-WEIXIN
	 // 小程序页面背景更新

	 uni.setPageStyle({
	   style: { backgroundColor: config.bg }
	 })
	 // #endif
      
	// #ifdef APP
	// APP导航栏处理
	uni.setNavigationBarColor({
	  frontColor: config.statusBar === 'dark' ? '#000000' : '#ffffff',
	  backgroundColor: config.navigationBar
	})
	// #endif
      
    }
  },
  getters: {
    themeConfig: (state) => THEME_CONFIG[state.currentTheme],
    isDarkTheme: (state) => state.currentTheme === 'dark'
  }
}